package com.dhy.handler;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import static com.dhy.TyporaImgManager.*;

/**
 * @author 大忽悠
 * @create 2022/5/27 10:05
 */
@Slf4j
public class LocalImgHandler extends AbstractImgHandler{
    /**
     * 如果是本地图片链接,那么将本地图片复制到本地git仓库中,然后git add-->git push
     * 返回github上图片的访问url
     * ![image-20220526193433388](https://raw.githubusercontent.com/dhyly/picBed/main/redisDeep/202205261934452.png)
     */
    @Override
    public String handle(String str) throws IOException {
        if (!str.startsWith(PATTERN)) {
            return str;
        }
        int begin = str.indexOf("(");
        int end = str.indexOf(")");
        String imgUrl = str.substring(begin + 1, end);
        if (imgUrl.startsWith(IGNORE_STR)) {
            return str;
        }
        log.info("图片的链接为: {}", imgUrl);
        File file = new File(imgUrl);
        //图片不存在,直接跳过
        if (!file.exists()) {
            return str;
        }
        //将图片复制到本地仓库中,然后git add
        File father = new File(gitLocalDir);
        if (!father.exists()) {
            throw new IllegalArgumentException("本地仓库[" + gitLocalDir + "]不存在");
        }
        File son = new File(gitLocalDir, dir);
        if (!son.exists()) {
            son.mkdirs();
        }
        String upLoadImgPath = gitLocalDir + File.separator + dir + File.separator + file.getName();
        Files.copy(Paths.get(file.toURI()), new FileOutputStream(upLoadImgPath));
        return str.substring(0, begin + 1) + urlPrefix + "//" + file.getName() + str.substring(end, str.length())+"\r\n";
    }

    @Override
    public Boolean afterHandle() {
        //改名
        File file = getLocalFile();
        File tempFile = getTempFile();
        file.renameTo(new File(file.getName() + ".old"));
        String tempFileName = tempFile.getName();
        tempFileName = tempFileName.substring(0, tempFileName.length() - 5);
        try {
            Files.copy(Paths.get(tempFile.toURI()), Paths.get(tempFile.getParent() + File.separator + tempFileName));
            Files.delete(Paths.get(tempFile.toURI()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return true;
    }

}
